package com.hengtiansoft.lfy.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;


import com.duowan.mobile.netroid.Request;
import com.hengtiansoft.lfy.LFYApplication;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.activity.FullScrenActivity;
import com.hengtiansoft.lfy.activity.LoginActivity;
import com.hengtiansoft.lfy.activity.LoginActivityV2;
import com.hengtiansoft.lfy.adapter.SceneDetailsAdapter;
import com.hengtiansoft.lfy.adapter.SceneDetailsAdapter.SceneDetailsAdapterListener;
import com.hengtiansoft.lfy.been.ChangeWords;
import com.hengtiansoft.lfy.been.Child;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.db.CL_InviteMessgeDao;
import com.hengtiansoft.lfy.download.DownloadManager;
import com.hengtiansoft.lfy.entity.CategroyEntity;
import com.hengtiansoft.lfy.entity.CollectionEntity;
import com.hengtiansoft.lfy.entity.ServiceResult;
import com.hengtiansoft.lfy.entity.WordsCategroyEntity;
import com.hengtiansoft.lfy.net.NetHelper;
import com.hengtiansoft.lfy.net.NetUtils;
import com.hengtiansoft.lfy.utils.CommonUtils;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.utils.Kdxf_TTSPlayer;
import com.hengtiansoft.pulltorefresh.PullToRefreshBase;
import com.hengtiansoft.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.hengtiansoft.pulltorefresh.PullToRefreshListView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class Change_ChineseEnglishFragment extends Fragment {
    private static String TAG = "ChineseEnglishFragment";
    private ListView mLvChineseEnglish;
    private SceneDetailsAdapter mSceneDetailsAdapter;
    public String childId;
    public String child_fen_id;
    private String title;
    private int page = 1;
    private List listWords = null;
    private ArrayList<HashMap<String, Object>> mList = new ArrayList<HashMap<String, Object>>();
    private PullToRefreshListView mPullListView;
    private boolean hasMoreData = true;
    private boolean hasData = true;
    private boolean isPullDownRefreshing; //正在下拉刷新
    private boolean isPullUpRefreshing;//正在上拉加载更多
    private SimpleDateFormat mDateFormat = new SimpleDateFormat("MM-dd HH:mm");
    private View v;
    private String isneedUpdate;
    private CL_InviteMessgeDao cl_inviteMessgeDao;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
      childId= getArguments().getString("child_id");
      child_fen_id= getArguments().getString("child_fen_id");
        isneedUpdate=getArguments().getString("isneedUpdate");
        cl_inviteMessgeDao=new CL_InviteMessgeDao(getActivity().getBaseContext());
                v = inflater.inflate(R.layout.fragment_chinese_english, container,
                        false);
            v.setTag(child_fen_id);
        return v;
    }
    public static Change_ChineseEnglishFragment newInstance(String child_id, String child_fen_id, String isneedUpdate) {
        Change_ChineseEnglishFragment change_ChineseEnglishFragment=new Change_ChineseEnglishFragment();
        Bundle tuijianBudle=new Bundle();
        tuijianBudle.putString("child_id", child_id);
        tuijianBudle.putString("child_fen_id",child_fen_id);
        tuijianBudle.putString("isneedUpdate",isneedUpdate);
        change_ChineseEnglishFragment.setArguments(tuijianBudle);
        return change_ChineseEnglishFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        childId = getArguments().getString("child_id");
        child_fen_id=getArguments().getString("child_fen_id");
        isneedUpdate=getArguments().getString("isneedUpdate");

    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if(isneedUpdate!=null&&"1".equals(isneedUpdate)){
            getWordsCategroyFromServer(child_fen_id+"",getActivity().getBaseContext());
        }else{
            showList();
        }

    }
    //网络请求
    public void getWordsCategroyFromServer(final String child_fen_id, final Context mContext){//GetChildCategroyJson getChildCategroyJson

        NetHelper.getWordsCategroyFromServer(getActivity(),child_fen_id, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                WordsCategroyEntity info = (WordsCategroyEntity) rspData;
                int code = info.getRetcode();
                List<ChangeWords> data = info.getData();
                String message = info.getMessage();
                if (code == 0) {
                    if (null != data) {
                        cl_inviteMessgeDao.upDatechildtype_isNeed_off(childId + "",child_fen_id);
                        cl_inviteMessgeDao.saveWordsNew(data, childId, child_fen_id);
                        showList();
                        isneedUpdate="0";
                    } else {
                        Toast.makeText(mContext, getString(R.string.get_scene_error),
                                Toast.LENGTH_LONG).show();
                    }
                }else{
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                }
            }
                    @Override
           public void failed(String msg) {
                        Toast.makeText(mContext, msg,
                                Toast.LENGTH_LONG).show();

           }
        }, WordsCategroyEntity.class);
    }
    AnimationDrawable anim;
    public  void showList() {



        Log.i("supeng", "cc=" + childId + "," + child_fen_id);
        title = getActivity().getIntent().getStringExtra("title");
        mPullListView = (PullToRefreshListView) v.findViewById(
                R.id.lv_chinese_english);
        // 上拉，下拉
        mPullListView.setPullLoadEnabled(true);
        mPullListView.setScrollLoadEnabled(false);
        mLvChineseEnglish = mPullListView.getRefreshableView();
       // mLvChineseEnglish.setDivider(null);
        Log.i(TAG, title);
        mPullListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                if (!CommonUtils.isNetWorkConnected(getActivity())) {
                    Toast.makeText(getActivity(),
                            getString(R.string.network_unavailable),
                            Toast.LENGTH_SHORT).show();
                    mPullListView.onPullDownRefreshComplete(); //加载完成
                    return;
                }
                isPullDownRefreshing = true;
                page=1;
                getList(page); //加载第一页
                setLastUpdateTime();
            }

            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                if (!CommonUtils.isNetWorkConnected(getActivity())) {
                    Toast.makeText(getActivity(),
                            getString(R.string.network_unavailable),
                            Toast.LENGTH_SHORT).show();
                    mPullListView.onPullUpRefreshComplete(); //加载完成
                    return;
                }

                isPullUpRefreshing = true;//上拉加载更多
               // int size = (mList.size() + 20) / 20;//加载第几页
                page++;
                getList(page);
            }
        });
        setLastUpdateTime();
        getList(page);
        mSceneDetailsAdapter = new SceneDetailsAdapter(getActivity(), mList);
        mLvChineseEnglish.setAdapter(mSceneDetailsAdapter);
        mSceneDetailsAdapter
                .setAdapterListener(new SceneDetailsAdapterListener() { //类似InterpretFragment 点击多出来的一行列表

                    @Override
                    public void onTranspondClick(int position) {

                    }

                    @Override
                    public void onPlayerTranslationClick(int position, View v) {
                        if (anim != null) {
                            anim.stop();
                            anim.selectDrawable(0);
                        }
                        ImageView ibtn_player_translation = null;
                        if (v.findViewById(R.id.ibtn_player_translation) != null) {
                            ibtn_player_translation = (ImageView) v.findViewById(R.id.ibtn_player_translation);
                        }
                        anim = (AnimationDrawable) ibtn_player_translation.getBackground();
                        Kdxf_TTSPlayer.getInstense().setStopListener(new Kdxf_TTSPlayer.StopListener() {
                            @Override
                            public void stop() {
                                anim.stop();
                                anim.selectDrawable(0);
                            }
                        });

                        anim.start();
                        String words_id = mSceneDetailsAdapter.getItem(position).get("words_id").toString();
                        String child_id = mSceneDetailsAdapter.getItem(position).get("child_id").toString();
                        String mp3path = DownloadManager.mSaveTranslateDirPath + "/" + child_id + "/" + words_id + ".mp3";
                        String wavpath = DownloadManager.mSaveTranslateDirPath + "/" + child_id + "/" + words_id + ".wav";
                        String synText = mSceneDetailsAdapter
                                .getItem(position).get("translation")
                                .toString();
                        if (fileIsExists(mp3path)) {
                            Kdxf_TTSPlayer.getInstense().TTSPlayOpu(mp3path, synText);
                            return;
                        } else if (fileIsExists(wavpath)) {
                            Kdxf_TTSPlayer.getInstense().TTSPlayOpu(wavpath, synText);
                            return;
                        }
                        if (CommonUtils.isNetWorkConnected(getActivity())) {

                            if (synText.length() <= 0)
                                return;
                            // TTSPlayer.getInstense().TTSPlay(synText);
                            Kdxf_TTSPlayer.getInstense().TTSPlay(synText, "", wavpath);
                        } else {
                            Toast.makeText(getActivity(), getString(R.string.check_network_no_cache),
                                    Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onOtherClick(int position) {
                    }

                    @Override
                    public void onItemClick(int position,View view) {
                        if("down".equals(view.getTag())){
                            mSceneDetailsAdapter.changeImageVisable(-1);
                            mSceneDetailsAdapter.notifyDataSetChanged();
                            view.setTag("right");
                        }else {
                            mSceneDetailsAdapter.changeImageVisable(position);
                            mSceneDetailsAdapter.notifyDataSetChanged();
                            if (position == mSceneDetailsAdapter.getCount() - 1) {
                                mLvChineseEnglish.setSelection(ListView.FOCUS_DOWN);
                            }
                            view.setTag("down");
                        }
                    }

                    @Override
                    public void onShareClick(int position) {
                        shared(mSceneDetailsAdapter.getItem(position)
                                .get("text").toString() + "\n"
                                + mSceneDetailsAdapter.getItem(position)
                                .get("translation").toString());
                    }

                    @Override
                    public void onCopyClick(int position) {
                        // 得到剪贴板管理器
                      /*  ClipboardManager cmb = (ClipboardManager) getActivity()
                                .getSystemService(Context.CLIPBOARD_SERVICE);
                        cmb.setText(mSceneDetailsAdapter.getItem(position)
                                .get("text").toString()
                                + "\n"
                                + mSceneDetailsAdapter.getItem(position)
                                        .get("translation").toString());
                        Toast.makeText(getActivity(), "已复制", Toast.LENGTH_LONG)
                                .show();*/
                        Intent intent = new Intent(getActivity(), com.hengtiansoft.lfy.widget.AlertDialog.class);
                        intent.putExtra("title", getString(R.string.copy_data));
                        intent.putExtra("showTitle", getString(R.string.copy_showtitle));
                        intent.putExtra("isCopy", true);
                        intent.putExtra("msg", mSceneDetailsAdapter.getItem(position)
                                .get("text").toString() + "\n"
                                + mSceneDetailsAdapter.getItem(position)
                                .get("translation").toString());
                        startActivity(intent);
                    }

                    @Override
                    public void onCollectClick(int position) {

                        //收藏
                        if (Config.isUserLogined()) {
                        String token=Config.getUserToken();
                            //添加收藏
                            if (mSceneDetailsAdapter.getItem(position)
                                    .get("collected").toString().equals("N")) {

                                String src_content=mSceneDetailsAdapter
                                        .getItem(position).get("text")
                                        .toString();
                                String des_content=mSceneDetailsAdapter
                                        .getItem(position)
                                        .get("translation").toString();
                                String username=Config.getUserName();
                                collection(token,src_content,des_content,username,   //AddCollect {"token":"dd529242e5c00ef9d71d076693d54207","src_content":"ss","des_content":"Ss","username":"qq_GZQBrx"}
                                        position,
                                        (Integer) mSceneDetailsAdapter
                                                .getItem(position).get("words_id"));

                            } else {
                                deletecollectRequest(token ,//DeleteCollect {"token":"dd529242e5c00ef9d71d076693d54207","collectid":"394"}
                                        mSceneDetailsAdapter
                                                .getItem(position)
                                                .get("collect_server_id").toString(),
                                        (Integer) mSceneDetailsAdapter
                                                .getItem(position).get("words_id"),
                                        position);
                                Log.i(TAG,
                                        "删除" + mSceneDetailsAdapter
                                                .getItem(position)
                                                .get("collect_server_id").toString());
                            }
                        } else {
                            startActivity(new Intent(getActivity(),
                                    LoginActivityV2.class).putExtra("from",
                                    "collection"));
//                            Toast.makeText(getActivity(), getString(R.string.not_login_title),
//                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFullClick(int position) {
                        startActivity(new Intent(getActivity(),
                                FullScrenActivity.class).putExtra(
                                "translate",
                                mSceneDetailsAdapter.getItem(position)
                                        .get("translation").toString()));
                    }
                });
    }
    //分享
    private void shared(final String body){
        final SHARE_MEDIA[] displaylist = new SHARE_MEDIA[]
                {
                        SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA,
                        SHARE_MEDIA.QQ, SHARE_MEDIA.SMS
                };
        new ShareAction(getActivity()).setDisplayList(displaylist)
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        if (share_media == SHARE_MEDIA.SMS) {
                            new ShareAction(getActivity()).setPlatform(share_media)
                                    .withText(body + "\n"+Constants.SHARE_URL)
                                    .withTitle("龙翻译")
                                    .share();

                        } else if(share_media== SHARE_MEDIA.WEIXIN_CIRCLE){
                            new ShareAction(getActivity()).setPlatform(share_media)
                                    .withText(body+"\n"+Constants.SHARE_URL)
                                    .withTitle("龙翻译")
                                    .withTargetUrl(Constants.SHARE_URL)
                                   // .withMedia(new UMImage(getActivity(), R.drawable.lfy))
                                    .share();
                        }
                        else {
                            new ShareAction(getActivity()).setPlatform(share_media)
                                    .withText(body)
                                    .withTitle("龙翻译")
                                    .withTargetUrl(Constants.SHARE_URL)
                                    .withMedia(new UMImage(getActivity(), R.drawable.lfy))
                                    .share();
                        }
                    }
                })
//                .setListenerList(new UMShareListener() {
//                    @Override
//                    public void onResult(SHARE_MEDIA share_media) {
//
//                    }
//
//                    @Override
//                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
//
//                    }
//
//                    @Override
//                    public void onCancel(SHARE_MEDIA share_media) {
//
//                    }
//                })
                .open();




    }


    //取消网络收藏
    private void deletecollectRequest(String token,String collectid, final int id,
                                      final int position) {
            NetHelper.deletecollectRequest(getActivity(), token, collectid, new NetUtils.NetCallBack<ServiceResult>() {
                @Override
                public void success(ServiceResult rspData) {
                    int code=rspData.getRetcode();
                    String message=rspData.getMessage();
                    if (code == 0) {
                        //listItem.get(position).put("serverId", -1);
                        //  listItem.get(position).put("collected", "N");
                        mList.get(position).put("collect_server_id",0);
                        mList.get(position).put("collected","N");
                        mSceneDetailsAdapter
                                .changeImageVisable(position);
                        mSceneDetailsAdapter.notifyDataSetChanged();
                        // updateDataForInterpretRecordDB(id, "N", -1);
                        cl_inviteMessgeDao.upDateCollect(id+"","N",0+"");
                        Toast.makeText(getActivity(), getString(R.string.unfavorite),
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getActivity(), message,
                                Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void failed(String msg) {
                    Toast.makeText(getActivity(), msg,
                            Toast.LENGTH_LONG).show();
                }
            },ServiceResult.class);
    }
    //添加收藏网络请求
    private void collection(String token,String src_content,String des_content,String username,final int pos, final int id) {
        NetHelper.collection(getActivity(),token,src_content,des_content,username,new NetUtils.NetCallBack<ServiceResult>(){

            @Override
            public void success(ServiceResult rspData) {
                CollectionEntity info= (CollectionEntity) rspData;
                int code=info.getRetcode();
                String message=info.getMessage();
                int data=info.getData();
                if (code == 0) {
                    //(int) data); //服务器返回serverId
                    mList.get(pos).put("collected", "Y");
                    mList.get(pos).put("collect_server_id", (int) data); //服务器返回serverId
                    mSceneDetailsAdapter.changeImageVisable(pos);
                    mSceneDetailsAdapter.notifyDataSetChanged();
                    cl_inviteMessgeDao.upDateCollect(id+"","Y",(int) data+"");
                    Toast.makeText(getActivity(), message,
                            Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getActivity(), message,
                            Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(getActivity(), msg,
                        Toast.LENGTH_LONG).show();
            }
        },CollectionEntity.class);

    }
    public boolean fileIsExists(String path){
        try{
            File f=new File(path);
            if(!f.exists()){
                return false;
            }

        }catch (Exception e) {

            return false;
        }
        return true;
    }
    private void setLastUpdateTime() {
        String text = formatDateTime(System.currentTimeMillis());
        mPullListView.setLastUpdatedLabel(text);
    }

    private String formatDateTime(long time) {
        if (0 == time) {
            return "";
        }
        return mDateFormat.format(new Date(time));
    }

    public void getList(int page) {
        if (isPullDownRefreshing) {
            mList.clear();
            hasMoreData = true;
            hasData = true;
        }
       listWords = cl_inviteMessgeDao.getSimilarResult(childId, child_fen_id, null,null, page);
        int size = listWords.size();
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                ChangeWords words = new ChangeWords();
                words = (ChangeWords) listWords.get(i);
                map.put("text", words.getSrc_content());
                map.put("translation", words.getDes_content());
                map.put("english_mp3path",words.getEnglish_mp3path());
                map.put("child_id",child_fen_id);
                map.put("childtype_id",words.getScenes_id());
                map.put("words_id",words.getId());
                map.put("collected",words.getWords_iscollect());
                map.put("collect_server_id",words.getCollect_server_id());
                mList.add(map);
                // Log.i(TAG, i + words.getChinese());
            }
        } else {
            Toast.makeText(getActivity(), getString(R.string.no_result), Toast.LENGTH_LONG).show();
            hasMoreData = false;//是否有更多的数据
            hasData = false;
        }
        //加载完成
        if (isPullDownRefreshing || isPullUpRefreshing) {
            mSceneDetailsAdapter.notifyDataSetChanged();
            mPullListView.onPullDownRefreshComplete();
            mPullListView.onPullUpRefreshComplete();
            mPullListView.setHasMoreData(hasMoreData);
            mPullListView.setHasData(hasData);
            isPullDownRefreshing = false;
            isPullUpRefreshing = false;
        }
    }

}
